package service

import "log"

type Handler func(c *Context) error

// AddHandler implements Engine
func (f *ServiceImp) AddHandler(t MessageType, h ...Handler) {
	if _, ok := f.HandlerMap[t]; !ok {
		f.HandlerMap[t] = make([]Handler, 0)
	} else {
		panic("already has handler for message type: " + string(t))
	}
	f.HandlerMap[t] = append(f.HandlerMap[t], h...)
}

func (f *ServiceImp) handleMessage(ctx *Context) {
	defer f.returnCtx(ctx)
	handlers, ok := f.HandlerMap[ctx.MsgType]
	if !ok {
		log.Println("no handler for message type:", ctx.MsgType)
		ctx.Conn.Close(nil)
	}

	h := func() error {
		for _, v := range handlers {
			if err := v(ctx); err != nil {
				return err
			}
		}
		return nil
	}

	ch := make(chan error, 1)
	select {
	case <-f.close:
		return
	case <-ctx.Done():
		return
	case ch <- h():
		err := <-ch
		if err != nil {
			log.Println("handle message error:", err)
			ctx.Conn.Close(nil)
		}
		close(ch)
	}
}
